import React, {useEffect, useState} from "react";
import {Alert, Dimensions, StyleSheet, Text, TextInput, TouchableHighlight, View} from "react-native";
import {cs, getBackgroundColor} from "./CommandCss/commandCss";
import {fontSize_15} from "./theme";
import {SvgXml} from "react-native-svg";
import {addSvgXml, subSvgXml} from "../libs/svgXml";
import {HeaderBackButton} from "@react-navigation/stack";
import {ArrayIsEqual} from "../libs/utils";
import {useFocusEffect} from "@react-navigation/native";
import {
    addAddressBook,
    addAddressBook_address,
    addressBookType,
    bookAddressType,
    removeAddressBook_address, updateAddressBook_name, updateAddressBook_remark
} from "./smartxL2Libs/L2_Data";
import SimpleToast from "react-native-simple-toast";
let canGoBack_addressBookAddView = true;
const {width,height,scale} = Dimensions.get("window");
const L2_AddressBookAddView = ({navigation,route}:any) => {
    //编辑还是新建 //false 为新建 true
    const [type,setType] = useState(route?.params?.type || false)
    const [name,setName] = useState(route?.params?.name || "")
    const [remark,setRemark] = useState(route?.params?.remark || "")
    const [addressList,setAddressList] = useState(route?.params?.addressList || [])

    const [nameInit,setNameInit] = useState(route?.params?.name || "")
    const [remarkInit,setRemarkInit] = useState(route?.params?.remark || "")
    const [addressListInit,setAddressListInit] = useState(route?.params?.addressList || [])
    const [saveInfo,setSaveInfo] = useState(false)
    useEffect(()=>{
        navigation.setOptions({
            title:`${type?'编辑':'新建'}联系人`,
        })
        const unsubscribe = navigation.addListener('beforeRemove', (e:any)=>{beforeRemove(e)})
        return unsubscribe
    },[])
    useEffect(()=>{
        if(!saveInfo)
        {
            return;
        }
        setSaveInfo(false)
        saveAddressBookView()
    },[saveInfo])
    useFocusEffect(
        React.useCallback(() => {
            setCanGoBack()
        },[])
    );
    const addNewInfo = (info:any) => {
        console.log(`addNewInfo`,info)
        canGoBack_addressBookAddView = false;
        //添加数据
        let addressListTemp:bookAddressType[] = [...addressList];
        addressListTemp.push(info);
        setAddressList(addressListTemp);
        console.log()
        setCanGoBack(undefined,undefined,addressListTemp)
    }
    const removeNewInfo = (info:any) => {
        console.log(`addNewInfo`,info)
        canGoBack_addressBookAddView = false;
        //移除数据
        let addressListTemp:bookAddressType[] = [...addressList];
        let index = addressListTemp.findIndex(item => item.address===info.address && item.chainID===info.chainID);
        if(index >= 0)
        {
            addressListTemp.splice(index,1)
        }
        setAddressList(addressListTemp);
        setCanGoBack(undefined,undefined,addressListTemp)
    }
    const setCanGoBack = (remarkNew?:string,nameNew?:string,addressListNew?:bookAddressType[]) => {
        console.log(addressListNew,addressListInit,addressList)
        console.log(ArrayIsEqual((addressListNew===undefined?addressList:addressListNew),addressListInit) && remarkInit===remark && name===nameInit,`name:${(nameNew===undefined?name:nameNew)}`,`nameInit:${nameInit}`,`remark:${(remarkNew===undefined?remark:remarkNew )}`,`remarkInit:${remarkInit}`)
        canGoBack_addressBookAddView = ArrayIsEqual((addressListNew===undefined?addressList:addressListNew),addressListInit) && remarkInit===(remarkNew===undefined?remark:remarkNew ) && (nameNew===undefined?name:nameNew)===nameInit;
        return canGoBack_addressBookAddView
    }
    const saveAddressBookView = async () => {
        console.log(name,remark,addressList)
        console.log(nameInit,remarkInit,addressListInit)
        //保存数据
        //创建
        if (!type) {
            let chainIDList: string[] = [];
            let addressListTemp = [...addressList];
            for (let i = 0; i < addressListTemp.length; i++) {
                if (chainIDList.length == 0) {
                    chainIDList.push(addressListTemp[i].chainID)
                    continue;
                }
                if (chainIDList.indexOf(addressListTemp[i].chainID) >= 0) {
                    continue;
                }
                chainIDList.push(addressListTemp[i].chainID)
            }
            console.log(`remark:${remark}`)
            let addressBookTemp: addressBookType = {
                name,
                remark,
                bookAddressList: addressList,
                chainIDList,
                timestamp:new Date().getTime()
            }
            console.log(addressBookTemp)
            let addAddressBookRes =  await addAddressBook(addressBookTemp)
            if(!addAddressBookRes.success)
            {
                SimpleToast.show(addAddressBookRes.falseReason)
                return ;
            }
        }
        //新建（修改）
        if(type)
        {
            let addressListTemp = [...addressList];
            console.log(addressListTemp)
            //移除的地址
            let removeAddressList:bookAddressType[] = [];
            for(let i = 0 ;i < addressListInit.length ; i++)
            {
                let index = addressListTemp.findIndex((item:bookAddressType)=>{
                    return item.address === addressListInit[i].address && item.chainID === addressListInit[i].chainID
                })
                if(index === -1)
                {
                    removeAddressList.push(addressListInit[i])
                }
            }
            for(let i = 0 ; i < removeAddressList.length ; i++)
            {
                let res = await removeAddressBook_address(nameInit,removeAddressList[i])
                if(!res.success)
                {
                    console.log(`removeAddressBook_address:false`)
                    SimpleToast.show(res.falseReason)
                    return
                }
            }
            //增加的地址
            let addAddressList:bookAddressType[] = [];
            for(let i = 0 ;i < addressListTemp.length ; i++)
            {
                let index = addressListInit.findIndex((item:bookAddressType)=>{
                    return item.address === addressListTemp[i].address && item.chainID === addressListTemp[i].chainID
                })
                if(index === -1)
                {

                    addAddressList.push(addressListTemp[i])
                }
            }
            for(let i = 0 ; i < addAddressList.length ; i++)
            {
                let res = await addAddressBook_address(nameInit,addAddressList[i])
                if(!res.success)
                {
                    console.log(`addAddressBook_address:false`,addressListTemp,addAddressList[i],addAddressList)
                    SimpleToast.show(res.falseReason)
                    return
                }
            }
            //修改名字
            if(name!==nameInit)
            {
                let res = await updateAddressBook_name(nameInit, name)
                if(!res.success)
                {
                    SimpleToast.show(res.falseReason)
                    return
                }
            }
            //修改备注
            if(remark!==remarkInit)
            {
                let res = await updateAddressBook_remark(name,remark )
                if(!res.success)
                {
                    SimpleToast.show(res.falseReason)
                    return
                }
            }
        }
        canGoBack_addressBookAddView = true;
        navigation.goBack();
    }
    const beforeRemove = (e: any) => {
        if(!canGoBack_addressBookAddView)
        {
            Alert.alert('', '联系人还没保存，确定保存吗', [{
                text: "取消",
                onPress: () => {
                    canGoBack_addressBookAddView = true;
                    navigation.goBack();
                },
                style: "cancel"
            }, {
                text: "确认",
                onPress:   () => {
                    setSaveInfo(true)

                }
            }]);
            e.preventDefault();
        }
    }

    return (
        <View style={styles.container}>
            <Text style={[cs.fs_16,cs.ta_l,cs.w_100]}>名字</Text>
            <TextInput
                placeholder={"请填写名字"}
                onChangeText={value => {setCanGoBack(undefined,value);setName(value)}}
                value={name}
                secureTextEntry={false}
                style={[
                    {borderBottomColor:"#f0f2f3"},cs.bbw_5s,
                    cs.w_100,cs.fs_15,cs.p0,cs.pt10,cs.pb10
                ]}
            />
            <Text style={[cs.fs_16,cs.ta_l,cs.w_100,cs.mt20]}>备注(可选)</Text>
            <TextInput
                placeholder={"请输入备注"}
                onChangeText={value => {
                    console.log(value)
                    setCanGoBack(value);
                    setRemark(value)
                }}
                value={remark}
                secureTextEntry={false}
                style={[
                    {borderBottomColor:"#f0f2f3"},cs.bbw_5s,
                    cs.w_100,cs.fs_15,cs.p0,cs.pt10,cs.pb10
                ]}
            />
            <TouchableHighlight
                underlayColor={"transparent"}
                style={[cs.w_100,cs.pt15,cs.pb15,cs.bbw_5s,{borderBottomColor:"#f0f2f3"}]}
                onPress={()=>{
                    navigation.navigate("L2_AddressBookAddAddressView",{addNewInfo})
                }}
            >
                <View style={[cs.fdRow]}>
                    <SvgXml xml={addSvgXml('white')} width={20} height={20} style={[{backgroundColor:"#01c885"},cs.borderRadioHalf]}/>
                    <Text style={[cs.fs_16,cs.ml10]}>添加钱包地址</Text>
                </View>
            </TouchableHighlight>
            {
                addressList.length?
                    addressList.map((item:bookAddressType,index:number)=>(
                        <TouchableHighlight
                            underlayColor={"transparent"}
                            style={[cs.w_100,cs.pt15,cs.pb15,cs.bbw_5s,{borderBottomColor:"#f0f2f3"}]}
                            onPress={()=>{
                                removeNewInfo(item)
                            }}
                            key={`addressList_${index}`}
                        >
                            <View style={[cs.fdRow,cs.ac]}>
                                <SvgXml xml={subSvgXml('white')} width={20} height={20} style={[{backgroundColor:"#fc4f4e"},cs.borderRadioHalf]}/>
                                <Text style={[cs.fs_16,cs.ml10,cs.mr10]}>{item.chainName}</Text>
                                <Text style={[cs.fs_14,cs.ml10,cs.f1]} >{item.address}</Text>
                            </View>
                        </TouchableHighlight>
                    ))
                    :null
            }


            <Text style={[
                cs.b20,cs.p10,cs.pl20,cs.pr20,
                cs.p_abs,cs.ta_c,cs.tav_c,
                cs.borderRadioHalf,getBackgroundColor(0),
                cs.c_w,cs.fs_13,cs.ls_half_0
            ]} onPress={()=>{
                saveAddressBookView()
            }}>
                保存
            </Text>

        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        paddingLeft: 20,
        paddingRight: 10,
        paddingTop:10,
        backgroundColor: "white"
    },
})
export default L2_AddressBookAddView;


